﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using FileSquirrel.Logic;
using FileSquirrel.Logic.XSD;
using FSquirrel.Properties;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using FSquirrel.Design;
using System.IO;
using System.Linq;
using System;

namespace FSquirrel.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class SettingsViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the SettingsViewModel class.
        /// </summary>
        public SettingsViewModel()
        {
            SettingsCommand = new RelayCommand<object>(DisplaySettings);
            BrowseCommand = new RelayCommand<string>(BrowseLibraryPath);
            CompleteCommand = new RelayCommand<object>(CompleteSettings);
            CatComboCommand = new RelayCommand<object>(CatComboSelected);
            UpdateCommand = new RelayCommand<object>(UpdateItem);
            DeleteCommand = new RelayCommand<object>(DeleteItem);
            AddCommand = new RelayCommand<object>(AddItem);
            ExtensionDropDownCommand = new RelayCommand<string>(ExtensionDropDownProcess);



        }

        private void PopulateCategories()
        {


            CategoryTable = Reader.UserSettings.Category;

            CategoryList.Clear();

            CategoryList.Add("Series");
            CategoryList.Add("Movies");
            CategoryList.Add("Music");
            CategoryList.Add("Ebooks");
            CategoryList.Add("Data");

        }

        #region Commands

        public RelayCommand<object> SettingsCommand { get; private set; }

        public RelayCommand<string> BrowseCommand { get; private set; }

        public RelayCommand<object> CompleteCommand { get; private set; }

        public RelayCommand<object> CatComboCommand { get; private set; }

        public RelayCommand<object> UpdateCommand { get; private set; }

        public RelayCommand<object> DeleteCommand { get; private set; }

        public RelayCommand<object> AddCommand { get; private set; }
        public RelayCommand<string> ExtensionDropDownCommand { get; private set; }

        #endregion Commands

        #region Methods

        private void DisplaySettings(object sender)
        {

            SettingsVisibility = !SettingsVisibility;
            //switch (SettingsVisibility)
            //{
            //    case Visibility.Visible:
            //        SettingsVisibility = Visibility.Collapsed;
            //        break;
            //    case Visibility.Collapsed:
            //        SettingsVisibility = Visibility.Visible;
            //        break;
            //}
        }

        private void CompleteSettings(object sender)
        {
            Properties.Settings.Default.Save();
            SettingsVisibility = false;
        }

        private void CatComboSelected(object sender)
        {
            if (sender is DataRowView)
            {
                var g = ((FileSquirrel.Logic.XSD.UserSettings.CategoryRow)(((DataRowView)(sender)).Row));
                CategoryPath = g.Path;
                Extensions = g.Extensions;
                CurrentCatItem = g.Name;
                NewAddText = "New";
            }

            NewItemEnabled = true;
            //ExtensionEnabled = true;
        }

        private void BrowseLibraryPath(string sender)
        {
            var dialog = new FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                switch (sender)
                {
                    case "Library":
                        Settings.Default.LibraryDir = dialog.SelectedPath;
                        Settings.Default.Save();
                        break;
                    case "Category":
                        CategoryPath = dialog.SelectedPath;
                        break;
                }
            }
        }

        private void UpdateItem(object sender)
        {
            var g = ((FileSquirrel.Logic.XSD.UserSettings.CategoryRow)(((DataRowView)(sender)).Row));
            UserSettings.CategoryRow catRow = Reader.UserSettings.Category.FindByNamePath(g.Name, g.Path);
            catRow.Name = CurrentCatItem;
            catRow.Path = CategoryPath;
            catRow.Extensions = Extensions;

            Reader.UserSettings.WriteXml(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XML\\UserSettings.xml"));
            CategoryTable = Reader.UserSettings.Category;
            NewAddText = "New";
        }

        private void DeleteItem(object sender)
        {
            var g = ((FileSquirrel.Logic.XSD.UserSettings.CategoryRow)(((DataRowView)(sender)).Row));
            Reader.UserSettings.Category.FindByNamePath(g.Name, g.Path).Delete();

            Reader.UserSettings.WriteXml(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XML\\UserSettings.xml"));
            CategoryTable = Reader.UserSettings.Category;
            CurrentCatItem = null;
            CategoryPath = string.Empty;
            Extensions = string.Empty;
            ExtensionEnabled = false;
            NewItemEnabled = false;
            NewAddText = "New";
        }

        private void ExtensionDropDownProcess(string ddaction)
        {
            if (ddaction.Equals("CLOSE"))
            {

                foreach (ExtensionModel exi in ExtensionList.Where(x => x.IsSelected == true).ToList<ExtensionModel>())
                {
                    if (!Extensions.ToUpperInvariant().Contains(exi.ExtensionName.ToUpperInvariant()))
                    {
                        Extensions += ";" + exi.ExtensionName.Replace(".", "");
                    }
                }
                foreach (ExtensionModel exi in ExtensionList.Where(x => x.IsSelected == false).ToList<ExtensionModel>())
                {
                    if (Extensions.ToUpperInvariant().Contains(exi.ExtensionName.ToUpperInvariant()))
                    {
                        Extensions = Extensions.Replace(exi.ExtensionName, "").Replace(";;", "");
                    }
                }
                if (Extensions.Length > 0 && Extensions.StartsWith(";"))
                {
                    Extensions = Extensions.Substring(1, Extensions.Length - 1);

                }
            }

            if (ddaction.Equals("OPEN"))
            {
                PopulateExtensionList();
                foreach (string sitem in Extensions.Split(';'))
                {
                    var g = ExtensionList.FirstOrDefault<ExtensionModel>(x => x.ExtensionName.Equals(sitem, System.StringComparison.InvariantCultureIgnoreCase));
                    if (g != null)
                    {
                        g.IsSelected = true;
                    }
                }
            }
            if (ddaction.Equals("CHANGE"))
            {
                Extensions = Extensions.Replace("FSquirrel.Design.ExtensionModel", "");
            }

        }

        private void AddItem(object sender)
        {
            switch (NewAddText)
            {
                case "New":
                    NewAddText = "Add";
                    CurrentCatItem = null;
                    CategoryPath = string.Empty;
                    Extensions = string.Empty;
                    //ExtensionEnabled = true;
                    NewItemEnabled = true;
                    break;
                case "Add":

                    UserSettings.CategoriesRow catsRow;

                    if (Reader.UserSettings.Categories.Count == 0)
                        catsRow = Reader.UserSettings.Categories.AddCategoriesRow();
                    else
                        catsRow = Reader.UserSettings.Categories[0];

                    UserSettings.CategoryRow catRow = Reader.UserSettings.Category.AddCategoryRow(CurrentCatItem, CategoryPath, Extensions, catsRow);

                    Reader.UserSettings.WriteXml(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XML\\UserSettings.xml"));

                    NewAddText = "New";

                    CurrentCatItem = null;
                    CategoryPath = string.Empty;
                    Extensions = string.Empty;
                    ExtensionEnabled = false;
                    NewItemEnabled = false;
                    break;
            }
        }

        private void PopulateExtensionList()
        {
            Extensions = string.Empty;
            if (Directory.Exists(CategoryPath))
            {
                ExtensionList.Clear();
                string[] fileExtensions = Directory.GetFiles(CategoryPath, "*.*", SearchOption.AllDirectories).Select(p => Path.GetExtension(p)).Distinct().OrderBy(p => p).ToArray();

                foreach (string item in fileExtensions)
                {
                    ExtensionList.Add(new ExtensionModel { ExtensionName = item.Replace(".", "") });
                }
                ExtensionEnabled = true;
            }
        }

        #endregion Methods

        #region Properties

        public const string SettingsVisibilityPropertyName = "SettingsVisibility";
        public const string ExtensionsPropertyName = "Extensions";
        public const string CategoryPathPropertyName = "CategoryPath";
        public const string CategoryTablePropertyName = "CategoryTable";
        public const string ExtensionEnabledPropertyName = "ExtensionEnabled";
        public const string CategoryListPropertyName = "CategoryList";
        public const string CurrentCatItemPropertyName = "CurrentCatItem";
        public const string NewAddTextPropertyName = "NewAddText";
        public const string ExtensionListPropertyName = "ExtensionList";
        public const string NewItemEnabledPropertyName = "NewItemEnabled";

        private bool _newitemenabled = false;

        public bool NewItemEnabled
        {
            get
            {
                return _newitemenabled;
            }

            set
            {
                if (_newitemenabled == value)
                {
                    return;
                }

                RaisePropertyChanging(NewItemEnabledPropertyName);
                _newitemenabled = value;
                RaisePropertyChanged(NewItemEnabledPropertyName);
            }
        }

        private ObservableCollection<ExtensionModel> _extensionlist = new ObservableCollection<ExtensionModel>();

        public ObservableCollection<ExtensionModel> ExtensionList
        {
            get
            {
                return _extensionlist;
            }

            set
            {
                if (_extensionlist == value)
                {
                    return;
                }

                RaisePropertyChanging(ExtensionListPropertyName);
                _extensionlist = value;
                RaisePropertyChanged(ExtensionListPropertyName);
            }
        }

        private bool _settingsvisibility = false;

        public bool SettingsVisibility
        {
            get
            {
                return _settingsvisibility;
            }

            set
            {
                var oldvalue = _settingsvisibility;
                if (_settingsvisibility == value)
                {
                    return;
                }

                RaisePropertyChanging(SettingsVisibilityPropertyName);
                _settingsvisibility = value;
                RaisePropertyChanged(SettingsVisibilityPropertyName);

                if (_settingsvisibility)
                {
                    PopulateCategories();
                }
                //RaisePropertyChanged(SettingsVisibilityPropertyName, oldvalue, _settingsvisibility, true);
            }
        }

        private string _extensions = string.Empty;

        public string Extensions
        {
            get
            {
                if (_extensions.Equals("FSquirrel.Design.ExtensionModel"))
                {
                    return string.Empty;
                }
                return _extensions;
            }

            set
            {
                if (_extensions == value)
                {
                    return;
                }

                RaisePropertyChanging(ExtensionsPropertyName);
                _extensions = value;
                RaisePropertyChanged(ExtensionsPropertyName);
            }
        }

        private string _categorypath;

        public string CategoryPath
        {
            get
            {
                return _categorypath;
            }

            set
            {
                if (_categorypath == value)
                {
                    return;
                }

                RaisePropertyChanging(CategoryPathPropertyName);
                _categorypath = value;
                RaisePropertyChanged(CategoryPathPropertyName);
                PopulateExtensionList();
            }
        }

        private DataTable _categorytable = new DataTable();

        public DataTable CategoryTable
        {
            get
            {
                return _categorytable;
            }

            set
            {
                if (_categorytable == value)
                {
                    return;
                }

                RaisePropertyChanging(CategoryTablePropertyName);
                _categorytable = value;
                RaisePropertyChanged(CategoryTablePropertyName);
            }
        }

        private bool _extensionenabled;

        public bool ExtensionEnabled
        {
            get
            {
                return _extensionenabled;
            }

            set
            {
                if (_extensionenabled == value)
                {
                    return;
                }

                RaisePropertyChanging(ExtensionEnabledPropertyName);
                _extensionenabled = value;
                RaisePropertyChanged(ExtensionEnabledPropertyName);
            }
        }

        private ObservableCollection<string> _categorylist = new ObservableCollection<string>();

        public ObservableCollection<string> CategoryList
        {
            get
            {
                return _categorylist;
            }

            set
            {
                if (_categorylist == value)
                {
                    return;
                }

                RaisePropertyChanging(CategoryListPropertyName);
                _categorylist = value;
                RaisePropertyChanged(CategoryListPropertyName);
            }
        }

        private string _currentcatitem = string.Empty;

        public string CurrentCatItem
        {
            get
            {
                return _currentcatitem;
            }

            set
            {
                if (_currentcatitem == value)
                {
                    return;
                }

                RaisePropertyChanging(CurrentCatItemPropertyName);
                _currentcatitem = value;
                RaisePropertyChanged(CurrentCatItemPropertyName);
            }
        }

        private string _newaddtext = "New";

        public string NewAddText
        {
            get
            {
                return _newaddtext;
            }

            set
            {
                if (_newaddtext == value)
                {
                    return;
                }

                RaisePropertyChanging(NewAddTextPropertyName);
                _newaddtext = value;
                RaisePropertyChanged(NewAddTextPropertyName);
            }
        }

        #endregion Properties
    }
}